package com.go.where.manager.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.json.simple.JSONObject;

import com.go.where.manager.common.Constants;
import com.go.where.manager.comparator.NameComparator;
import com.go.where.manager.comparator.SizeComparator;
import com.go.where.manager.comparator.TypeComparator;
import com.go.where.manager.exception.ManagerException;

public class KindEditUtil {

	private static final Logger log = Logger.getLogger(KindEditUtil.class);

	/**
	 * 上传图片
	 * 
	 * @param activityInfo
	 * @param picture
	 * @param pictureFileName
	 * @throws UnsupportedEncodingException
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static String uploadPicture(File picture, String pictureFileName,
			String picRealpath, String zoomPicPath)
			throws UnsupportedEncodingException, FileNotFoundException,
			IOException {
		StringBuilder picPath = new StringBuilder();
		ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
		String realpath = picRealpath;
		File file = picture;
		if (file != null) {
			File savedir = new File(realpath);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
			String newFileName = DateUtil.format(new Date(), "yyyyMMddHHmmss")
					+ "_" + CommonUtil.createRandomNumber()
					+ pictureFileName.substring(pictureFileName.indexOf("."));
			FileOutputStream fos = new FileOutputStream(realpath
					+ CommonUtil.FILE_SEPARATOR + newFileName);
			picPath.append(CommonUtil.FILE_SEPARATOR + zoomPicPath);

			picPath.append(Constants.ZOOM_PATH + CommonUtil.FILE_SEPARATOR
					+ newFileName);
			try {
				CompressPicUtil.compressPicture(realpath, newFileName, file);
				FileInputStream fis = new FileInputStream(file);
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = fis.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
				fis.close();
				fos.close();
			} catch (Exception e) {
				log.error("", e);
			}
		}
		return picPath.toString();
	}

	/**
	 * 拼接html文件内容
	 * 
	 * @param htmlData
	 * @param title
	 * @param saveOrEdit
	 * @return
	 */
	public static StringBuilder linkHtml(String htmlData, String title,
			boolean saveOrEdit) {
		StringBuilder sb = new StringBuilder();
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		sb
				.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
		sb
				.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">");
		sb.append("<head>");
		sb.append("<title>");
		sb.append(title);
		sb.append("</title>");
		sb
				.append("<meta http-equiv=\"Cache-Control\" content=\"no-cache, no-store, must-revalidate\" />");
		sb.append("<meta http-equiv=\"Pragma content=\"no-cache\" />");
		sb.append("<meta http-equiv=\"Expires\" content=\"0\" />");
		sb
				.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />");

		sb
				.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />");

		sb
				.append("<link href=\"gowhere.css\" rel=\"stylesheet\" type=\"text/css\" />");
		sb
				.append("<link href=\"rich_media.css\" rel=\"stylesheet\" type=\"text/css\" />");
		sb
				.append("<script type=\"text/javascript\" src=\"jquery.js\"></script>");
		sb
				.append("<script type=\"text/javascript\" src=\"control.js\"></script>");
		sb.append("</head>");
		sb.append("<body>");
		if (saveOrEdit) {
			sb.append("<div class=\"rich_media\"><div class=\"p\">");
			sb.append("<h2 class=\"rich_media_title\" id=\"activity-name\">");
			sb.append(title);
			sb.append("</h2>");
			sb.append("<div class=\"rich_media_meta_list\">");
			sb
					.append("<em id=\"post-date\" class=\"rich_media_meta rich_media_meta_text\">");
			sb.append(DateUtil.format(new Date()));
			sb.append("</em></div>");
			sb.append(htmlData);
			sb.append("</div></div>");
		} else {
			if (htmlData.indexOf("<div class=\"rich_media\">") != -1
					&& htmlData.indexOf("<div class=\"p\">") != -1) {
				sb.append(htmlData);
			} else if (htmlData.indexOf("<div class=\"rich_media\">") == -1
					&& htmlData.indexOf("<div class=\"p\">") != -1) {
				sb.append("<div class=\"rich_media\">");
				sb.append(htmlData);
				sb.append("</div>");
			} else if (htmlData.indexOf("<div class=\"rich_media\">") != -1
					&& htmlData.indexOf("<div class=\"p\">") == -1) {
				sb.append("<div class=\"p\">");
				sb.append(htmlData);
				sb.append("</div>");
			} else {
				sb.append("<div class=\"rich_media\"><div class=\"p\">");
				sb.append(htmlData);
				sb.append("</div></div>");
			}
		}
		sb.append("</body>");
		sb.append("</html>");
		return sb;
	}

	/**
	 * 富文本编辑器中上传图片
	 * 
	 * @param request
	 * @param response
	 * @param out
	 * @param path
	 * @return
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	@SuppressWarnings("unchecked")
	public static String uploadImage(HttpServletRequest request,
			HttpServletResponse response, PrintWriter out, String path)
			throws IOException, FileNotFoundException {
		path = Constants.MATERIAL_HTML + path;
		String savePath = ServletActionContext.getServletContext().getRealPath(
				CommonUtil.FILE_SEPARATOR)
				+ path;
		File imgPath = new File(savePath);
		if (!imgPath.exists()) {
			imgPath.mkdirs();
		}
		// 文件保存目录URL
		String saveUrl = request.getContextPath() + CommonUtil.FILE_SEPARATOR
				+ path;

		// 定义允许上传的文件扩展名
		HashMap<String, String> extMap = new HashMap<String, String>();
		extMap.put("image", "gif,jpg,jpeg,png,bmp");
		extMap.put("flash", "swf,flv");
		extMap.put("media",
				"swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
		extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

		response.setContentType("text/html; charset=UTF-8");
		if (!ServletFileUpload.isMultipartContent(request)) {
			out.print(getError("请选择文件。"));
			throw new ManagerException("err");
			// return "err";
		}
		// 检查目录
		File uploadDir = new File(savePath);
		if (!uploadDir.isDirectory()) {
			out.print(getError("上传目录不存在。"));
			throw new ManagerException("err");
			// return "err";
		}
		// 检查目录写权限
		if (!uploadDir.canWrite()) {
			out.print(getError("上传目录没有写权限。"));
			throw new ManagerException("err");
			// return "err";
		}

		String dirName = request.getParameter("dir");
		if (dirName == null) {
			dirName = "image";
		}
		if (!extMap.containsKey(dirName)) {
			out.print(getError("目录名不正确。"));
			throw new ManagerException("err");
			// return "err";
		}
		// 创建文件夹
		savePath += dirName + CommonUtil.FILE_SEPARATOR;
		saveUrl += dirName + CommonUtil.FILE_SEPARATOR;
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + CommonUtil.FILE_SEPARATOR;
		saveUrl += ymd + CommonUtil.FILE_SEPARATOR;
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
		String fileName = wrapper.getFileNames("imgFile")[0];
		File file = wrapper.getFiles("imgFile")[0];

		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)
				.toLowerCase();
		if (!Arrays.asList(extMap.get(dirName).split(",")).contains(fileExt)) {
			out.print(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName)
					+ "格式。"));
			throw new ManagerException("err");
			// return "err";
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String newFileName = df.format(new Date()) + "_"
				+ new Random().nextInt(1000) + "." + fileExt;
		saveUrl += newFileName;
		// 压缩图片
		if (Arrays.asList(extMap.get("image").split(",")).contains(fileExt)) {
			CompressPicUtil.compressPicture(savePath + newFileName, file);
		}
		if (Arrays.asList(extMap.get("media").split(",")).contains(fileExt)) {
			FileOutputStream fos = new FileOutputStream(savePath + newFileName);
			byte[] buffer = new byte[1024];
			InputStream in = new FileInputStream(file);
			try {
				int num = 0;
				while ((num = in.read(buffer)) > 0) {
					fos.write(buffer, 0, num);
				}
			} catch (Exception e) {
				log.error("", e);
			} finally {
				try {
					if (in != null)
						in.close();
					if (fos != null)
						fos.close();
				} catch (IOException e) {
				}
			}
		}

		JSONObject obj = new JSONObject();
		obj.put("error", 0);
		obj.put("url", saveUrl);
		return obj.toJSONString();
	}

	/**
	 * 富文本编辑器中文件管理
	 * 
	 * @param request
	 * @param out
	 * @param mPath
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static JSONObject fileManager(HttpServletRequest request,
			PrintWriter out, String mPath) {
		mPath = Constants.MATERIAL_HTML + mPath;
		// 根目录路径，可以指定绝对路径，比如 /var/www/attached/
		String rootPath = ServletActionContext.getServletContext().getRealPath(
				CommonUtil.FILE_SEPARATOR)
				+ mPath;
		// 根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
		String rootUrl = request.getContextPath() + CommonUtil.FILE_SEPARATOR
				+ mPath;
		// 图片扩展名
		String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
		String dirName = request.getParameter("dir");
		if (dirName != null) {
			if (!Arrays.<String> asList(
					new String[] { "image", "flash", "media", "file" })
					.contains(dirName)) {
				out.println("Invalid Directory name.");
				throw new ManagerException("");
				// return null;
			}
			rootPath += dirName + CommonUtil.FILE_SEPARATOR;
			rootUrl += dirName + CommonUtil.FILE_SEPARATOR;
			File saveDirFile = new File(rootPath);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
		}
		// 根据path参数，设置各路径和URL
		String path = request.getParameter("path") != null ? request
				.getParameter("path") : "";
		String currentPath = rootPath + path;
		String currentUrl = rootUrl + path;
		String currentDirPath = path;
		String moveupDirPath = "";
		if (!"".equals(path)) {
			String str = currentDirPath.substring(0,
					currentDirPath.length() - 1);
			moveupDirPath = str.lastIndexOf(CommonUtil.FILE_SEPARATOR) >= 0 ? str
					.substring(0,
							str.lastIndexOf(CommonUtil.FILE_SEPARATOR) + 1)
					: "";
		}
		// 排序形式，name or size or type
		String order = request.getParameter("order") != null ? request
				.getParameter("order").toLowerCase() : "name";
		// 不允许使用..移动到上一级目录
		if (path.indexOf("..") >= 0) {
			out.println("Access is not allowed.");
			throw new ManagerException("");
			// return null;
		}
		// 最后一个字符不是/
		if (!"".equals(path) && !path.endsWith(CommonUtil.FILE_SEPARATOR)) {
			out.println("Parameter is not valid.");
			throw new ManagerException("");
			// return null;
		}
		// 目录不存在或不是目录
		File currentPathFile = new File(currentPath);
		if (!currentPathFile.isDirectory()) {
			out.println("Directory does not exist.");
			throw new ManagerException("");
			// return null;
		}
		// 遍历目录取的文件信息
		List<Hashtable> fileList = new ArrayList<Hashtable>();
		if (currentPathFile.listFiles() != null) {
			for (File file : currentPathFile.listFiles()) {
				Hashtable<String, Object> hash = new Hashtable<String, Object>();
				String fileName = file.getName();
				if (file.isDirectory()) {
					hash.put("is_dir", true);
					hash.put("has_file", (file.listFiles() != null));
					hash.put("filesize", 0L);
					hash.put("is_photo", false);
					hash.put("filetype", "");
				} else if (file.isFile()) {
					String fileExt = fileName.substring(
							fileName.lastIndexOf(".") + 1).toLowerCase();
					hash.put("is_dir", false);
					hash.put("has_file", false);
					hash.put("filesize", file.length());
					hash.put("is_photo", Arrays.<String> asList(fileTypes)
							.contains(fileExt));
					hash.put("filetype", fileExt);
				}
				hash.put("filename", fileName);
				hash.put("datetime",
						new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file
								.lastModified()));
				fileList.add(hash);
			}
		}

		if ("size".equals(order)) {
			Collections.sort(fileList, new SizeComparator());
		} else if ("type".equals(order)) {
			Collections.sort(fileList, new TypeComparator());
		} else {
			Collections.sort(fileList, new NameComparator());
		}
		JSONObject result = new JSONObject();
		result.put("moveup_dir_path", moveupDirPath);
		result.put("current_dir_path", currentDirPath);
		result.put("current_url", currentUrl);
		result.put("total_count", fileList.size());
		result.put("file_list", fileList);
		return result;
	}

	@SuppressWarnings("unchecked")
	public static String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toJSONString();
	}
}
